package service

import (
	"go-ecommerce/internal/model"
	"gorm.io/gorm"
)

// AssignPermissions 给角色分配权限（先清空再插入）
func AssignPermissions(db *gorm.DB, roleID uint64, permIDs []uint64) error {
	// 先删除旧权限
	db.Where("role_id = ?", roleID).Delete(&model.RolePermission{})

	// 插入新权限
	var list []model.RolePermission
	for _, pid := range permIDs {
		list = append(list, model.RolePermission{
			RoleID:       roleID,
			PermissionID: pid,
		})
	}
	return db.Create(&list).Error
}

// GetRolePermissionIDs 查询角色绑定的权限ID列表
func GetRolePermissionIDs(db *gorm.DB, roleID uint64) ([]uint64, error) {
	var list []model.RolePermission
	var ids []uint64
	err := db.Where("role_id = ?", roleID).Find(&list).Error
	if err != nil {
		return nil, err
	}
	for _, item := range list {
		ids = append(ids, item.PermissionID)
	}
	return ids, nil
}
